<template>
  <div class="commodity">
    <nav-bar></nav-bar>
    <div class="commodity-page clearfix" v-loading.body="loading">
      <div class="left">
        <div class="img-container">
          <img :src="product.pic"/>
        </div>
        <div class="same" v-if="same && same.length !== 0">
          <div class="xyd-container">
            <div class="xyd-c-title">同类产品</div>
            <div class="xyd-c-content">
              <ul>
                <li v-for="item,i in same" :key="same">
                  <book-item :value="item"></book-item>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <div class="middle">
        <div class="name">{{product.title}}</div>
        <div class="description" >
          简介：<span v-html="">{{product.intro | getSimpleText}}</span>
        </div>
        <div class="info">
          <div class="author">
            <span>作者：{{product.author}}&nbsp;&nbsp;&nbsp;&nbsp;出版社：{{product.publish}}&nbsp;&nbsp;&nbsp;&nbsp;出版时间：{{product.pub_date}}</span>
          </div>
          <div class="rate-container">
            <div>
              <el-rate
                :value="product.star / 2"
                disabled
              >
              </el-rate>
            </div>
            <span>{{product.star}}分</span>
          </div>
        </div>
        <div class="money">
          <span class="price1">¥{{product.real_price}}</span>
          <span class="price2">¥{{product.origin_price}}</span>
          <span class="discount">（{{product.discount}}折）</span>
          <label class="free_ship" v-if="product.free_ship" for="">包邮</label>
          <label class="freight" v-if="!product.free_ship" for="">运费：{{product.freight}}</label>
        </div>
        <div class="address">
          <label for="">配送至</label>
          <el-select
            v-model="value1"
            placeholder="选择省份"
            @change="handleChange1"
            style="width:127px;"
          >
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select
            v-model="value2"
            placeholder="选择城市"
            @change="handleChange2"
            style="width:127px;"
          >
            <el-option
              v-for="item in options2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select
            v-model="value3"
            placeholder="选择区县"
            @change="handleChange3"
            style="width:127px;"
          >
            <el-option
              v-for="item in options3"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="buy">
          <div class="buy-input">
            <el-input-number v-model="num1" @change="handleChange" :min="1" :max="10"></el-input-number>
          </div>
          <div class="btn-group">
            <button class="yellow2-btn" @click="addToCart">加入购物车</button>
            <button class="orange-btn" @click="buyNow">立即购买</button>
          </div>
        </div>
        <div class="info-item">
          <ul>
            <li>版次：1</li>
            <li>印刷时间：{{product.print_time}}</li>
            <li>印次：1</li>
            <li>页数：{{product.page}}</li>
            <li>开本：{{product.format}}</li>
            <li>包装：{{product.package}}</li>
            <li>字数：{{product.words}}</li>
            <li>纸张：{{product.paper}}</li>
            <li>是否套装：{{product.suit ? '是' : '否'}}</li>
          </ul>
        </div>
        <div class="category" v-if="product.category">
          所属分类：{{product.category.pcat}} > {{product.category.cat}}
        </div>
        <div class="adv">
          <el-carousel height="120px" trigger="click" arrow="never" :interval="5000">
            <el-carousel-item v-for="item in ads" :key="item">
              <img :src="item.image_url"/>
            </el-carousel-item>
          </el-carousel>
        </div>
        <div class="com-fieldset">
          <div class="title">编辑推荐</div>
          <div class="content simditor" >
            <div class="simditor-body" v-html="product.editor"></div>
          </div>
        </div>
        <div class="com-fieldset">
          <div class="title">内容简介</div>
          <div class="content simditor" >
            <div class="simditor-body" v-html="product.summary"></div>
          </div>
        </div>
        <div class="com-fieldset">
          <div class="title">作者简介</div>
          <div class="content simditor">
            <div class="simditor-body" v-html="product.author_intro"></div>
          </div>
        </div>
        <div class="com-fieldset">
          <div class="title">目录</div>
          <div class="content simditor" >
            <div class="simditor-body" v-html="product.catalog"></div>
          </div>
        </div>
        <div class="com-fieldset">
          <div class="title">商品评论</div>
          <div class="content clearfix">
            <div class="comment">
              <div class="percent">{{good_rate.toFixed(1)}}%</div>
              <div class="text">好评度</div>
            </div>
            <div class="rate-group">
              <div class="rate-container">
                <div class="rate-value">
                  <div class="rate-content1" :style="good + mid + bad === 0 ? 'width:0' : `width:${good / (good + mid + bad) * 138}px`"></div>
                </div><span>好评（{{good}}人）</span>
              </div>
              <div class="rate-container">
                <div class="rate-value">
                  <div class="rate-content2" :style="good + mid + bad === 0 ? 'width:0' : `width:${mid / (good + mid + bad) * 138}px`"></div>
                </div><span>中评（{{mid}}人）</span>
              </div>
              <div class="rate-container">
                <div class="rate-value">
                  <div class="rate-content3" :style="good + mid + bad === 0 ? 'width:0' : `width:${bad / (good + mid + bad) * 138}px`"></div>
                </div><span>差评（{{bad}}人）</span>
              </div>
            </div>
            <div class="btn-group">
              <button class="green-btn" v-if="$store.state.user.uid" @click="commentBox = !commentBox">{{commentBox ? '收起评论' : '我要评论'}}</button>
            </div>
          </div>
        </div>
        <div class="comment-box" v-if="commentBox">
          <el-rate
            class="comment-rate"
            v-model="rateStar"
            :texts="['差评', '中评', '中评', '好评', '好评']"
            show-text>
          </el-rate>
          <el-input
            class="comment-input"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入内容"
            v-model="rateText">
          </el-input>
          <div class="comment-bottom clearfix">
            <button class="ion-image" @click="uploadCommentPic"></button>
            <ul class="img-container">
              <li></li>
            </ul>
            <el-button class="comment-btn" size="small" @click="handleComment">发表评论</el-button>
          </div>
        </div>
        <div class="comment-title">
          <ul>
            <li><a @click="handlefilter(3)" :style="num === 3 ? 'color: #00A2EA' : ''">全部（{{good + mid + bad}}）</a></li>
            <li><a @click="handlefilter(0)" :style="num === 0 ? 'color: #00A2EA' : ''">好评（{{good}}）</a></li>
            <li><a @click="handlefilter(1)" :style="num === 1 ? 'color: #00A2EA' : ''">中评（{{mid}}）</a></li>
            <li><a @click="handlefilter(2)" :style="num === 2 ? 'color: #00A2EA' : ''">差评（{{bad}}）</a></li>
            <li><a @click="handlefilter(4)" :style="num === 4 ? 'color: #00A2EA' : ''">晒图（{{pic}}）</a></li>
          </ul>
        </div>
        <ul class="comment-list">
          <comment-item :value="item" v-for="item,i in comments" :key="i"></comment-item>
        </ul>
        <div class="pagination-container">
          <el-pagination
            v-if="comments && comments.length !== 0"
            :page-size="offset"
            layout="prev, pager, next"
            :total="total"
            :current-page="page"
            @current-change="handlePageChange"
          >
          </el-pagination>
        </div>
      </div>
      <div class="right">
        <div>
          <img :src="shop.logo" style="width:100%;" />
          <div style="padding:10px 0;">{{shop.shopname}}</div>
        </div>
        <div class="btn-group">
          <button class="yellow-btn" @click="goShopcar"><i class="ion-android-cart"></i>购物车</button>
          <button class="orange-btn" @click="goOrder"><i class="ion-android-list"></i>我的订单</button>
        </div>
        <div class="xyd-container">
          <div class="xyd-c-title">推广产品</div>
          <div class="xyd-c-content">
            <ul>
              <li v-for="item,i in recommend" :key="i">
                <book-item :value="item"></book-item>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import store from '@/assets/mock_images/store.png'
  import book3 from '@/assets/mock_images/book3.png'
  import adv2 from '@/assets/mock_images/adv2.png'
  import { NavBar } from 'views/layout'
  import { getShopDetail, addShopCart, getComment, pushComment } from 'api/shop'
  import { getAddress } from 'api/common'
  import BookItem from './bookItem'
  import CommentItem from './commentItem'
  import { param } from 'utils/index'
  import { getSimpleText } from 'utils/filters/index'
  import pick from 'utils/file/picker'

  export default {
    name: 'commodity',
    components: {
      NavBar,
      BookItem,
      CommentItem
    },
    data() {
      return {
        store,
        book3,
        shop: {},
        adv2,
        good_rate: 0,
        good: 0,
        mid: 0,
        bad: 0,
        pic: 0,
        product: {},
        recommend: [],
        comments: [],
        page: 1,
        total: 0,
        offset: 10,
        level: null,
        isPic: null,
        ads: [],
        same: [],
        num1: 1,
        city: '',
        options1: [],
        options2: [],
        options3: [],
        value1: '',
        value2: '',
        value3: '',
        loading: false,
        commentBox: false,
        rateStar: 0,
        rateText: '',
        num: 3
      }
    },
    created() {
      this.routerChange(this.$route)
    },
    methods: {
      // 路由变化
      routerChange(route) {
        const { id } = route.params
        this.fetchAddress(1)
        this.loading = true
        getShopDetail({
          pid: id
        })
        .then(res => {
          this.bad = res.data.bad
          this.good = res.data.good
          this.good_rate = res.data.good_rate
          this.mid = res.data.mid
          this.pic = res.data.pic
          this.product = res.data.product
          this.recommend = res.data.recommend
          this.same = res.data.same
          this.shop = res.data.shop
          this.ads = res.data.ads
          this.loading = false
        })
        .catch(err => {
          console.log(err)
          this.loading = false
        })
        // 获取评论
        this.fetchComments()
      },
      // 获取评论
      fetchComments(params = {}) {
        const { id } = this.$route.params
        this.loading = true
        getComment({
          pid: id,
          type: 0,
          page: this.page,
          level: this.level,
          pic: this.isPic,
          ...params
        })
        .then(res => {
          this.loading = false
          this.comments = res.data
          this.total = res.page.last_page * this.offset
        })
        .catch(err => {
          this.loading = false
          console.log(err)
        })
      },
      // 筛选评论
      handlefilter(num) {
        this.num = num
        if (num === 3) {
          this.level = null
          this.isPic = null
          this.page = 1
          this.fetchComments()
        } else if (num === 0 || num === 1 || num === 2) {
          this.level = num
          this.isPic = null
          this.page = 1
          this.fetchComments()
        } else if (num === 4) {
          this.level = null
          this.isPic = 1
          this.page = 1
          this.fetchComments()
        }
      },
      fetchAddress(num, val = {}) {
        getAddress(val)
        .then(res => {
          this[`options${num}`] = res.city
        })
        .catch(err => console.log(err))
      },
      handleChange(value) {
        // v-model自动改了num1
        console.log(value);
      },
      // 选择省，获取市
      handleChange1(val) {
        this.city = val
        this.fetchAddress(2, { city: val })
      },
      // 选择市，获取区
      handleChange2(val) {
        this.city = val
        this.fetchAddress(3, { city: val })
      },
      // 选择区
      handleChange3(val) {
        this.city = val
      },
      goShopcar() {
        this.$router.push('/mall/shopcar?type=0')
      },
      goOrder() {
        this.$router.push('/mall/order-list?type=0')
      },
      // 加入购物车
      addToCart() {
        const { id } = this.$route.params
        addShopCart({
          pid: id,
          amount: this.num1,
          p: 0
        })
        .then(res => {
          console.log(res)
          this.$message({
            message: '成功加入购物车',
            type: 'success'
          })
        })
        .catch(err => console.log(err))
      },
      // 立即购买
      buyNow() {
        const { id, pic, title, intro, real_price, freight } = this.product
        const { shop_id, shopname } = this.shop
        const query = param({
          type: 0,
          pid: id,
          pic,
          title,
          intro: getSimpleText(intro).slice(0, 50),
          price: real_price,
          freight,
          shop_id,
          shop_name: shopname,
          amount: this.num1
        })
        if (!this.$store.state.user.uid) {
          this.$alert('您还未登录，请先登录', '提示', {
            confirmButtonText: '确定',
            type: 'waening',
            callback: action => {
              console.log(action)
            }
          })
          return false
        }
        this.$router.push('/mall/shopcar/0?' + query)
      },
      handlePageChange(page) {
        this.page = page
        this.fetchComments()
      },
      // 评论上传图片
      uploadCommentPic() {
        pick('image')
        .then(file => {
          console.log(file)
        })
        .catch(err => console.log(err))
      },
      // 发表评论
      handleComment() {
        const { id } = this.$route.params
        if (this.rateStar === 0) {
          this.$message({
            message: '您还没评分',
            type: 'warning'
          })
          return false
        }
        pushComment({
          content: this.rateText,
          star: this.rateStar,
          ispic: '',
          pid: id,
          level: this.rateStar === 1 ? 2 : (this.rateStar === 2 || this.rateStar === 3) ? 1 : 0,
          type: 0
        })
        .then(res => {
          console.log(res)
          // location.reload()
          this.$message({
            message: '发表成功',
            type: 'success'
          })
          this.commentBox = false
          this.page = 1
          this.rateStar = 0
          this.rateText = ''
          this.fetchComments()
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: 'error'
          })
        })
      }
    },
    watch: {
      '$route'(to, from) {
        this.routerChange(this.$route)
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import '../../styles/simditor.css';
  @import '../../styles/mixin.scss';
  .commodity{
    .commodity-page{
      width: 1200px;
      margin: 0 auto;
      .left{
        float: left;
        width: 210px;
        .img-container{
          height: 337px;
          padding: 50px 0;
          background-color: #f4f4f4;
          text-align: center;
          margin-bottom: 30px;
          >img{
            width: 100%;
          }
        }
        .xyd-container{
          .xyd-c-title{}
          .xyd-c-content{
            >ul{
              >li{
                &:last-child{
                  border-bottom: 0;
                }
                border-bottom: 1px solid #e5e6e7;
              }
            }
          }
        }
      }
      .middle{
        float: left;
        width: 720px;
        margin: 0 30px;
        .name{
          font-size: 24px;
          @include ellipsisLn(2)
        }
        .description{
          margin: 10px 0 20px 0;
          @include ellipsisLn(3)
        }
        .info{
          padding: 14px 0;
          .author{
            vertical-align: middle;
            display: inline-block;
            line-height: 30px;
            @include ellipsis(530px)
          }
          .rate-container{
            display: inline-block;
            line-height: 30px;
            width: 180px;
            vertical-align: middle;
            >div{
              display: inline-block;
              vertical-align: middle;
            }
            >span{
              color: #EF7401;
              font-size: 16px;
              font-weight: 500;
            }
          }
        }
        .money{
          height: 44px;
          line-height: 44px;
          background-color: #f4f4f4;
          padding: 0 20px;
          .price1{
            font-size: 22px;
            color: #EF6401;
          }
          .price2{
            color: #999;
            text-decoration:line-through;
          }
          .discount{
            color: #999;
          }
          >label.free_ship{
            background-color: #EFA901;
            padding: 3px 10px;
            color: #fff;
          }
          >label.freight{
            background-color: #37C3E4;
            padding: 3px 10px;
            color: #fff;
          }
        }
        .address{
          padding: 15px 0;
        }
        .buy{
          padding: 20px 0;
          border-bottom: 1px solid #e5e6e7;
          .buy-input{
            display: inline-block;
            vertical-align: middle;
          }
          .btn-group{
            float: right;
            >button{
              vertical-align: middle;
              width: 240px;
              height: 38px;
              font-size: 16px;
            }
          }
        }
        .info-item{
          >ul{
            >li{
              line-height: 24px;
              float: left;
              width: 240px;
            }
          }
        }
        .category{
          line-height: 30px;
        }
        .adv{
          img{
            // width: 100%;
            height: 100%;
          }
        }
        .com-fieldset{
          margin-top: 20px;
          .title{
            font-size: 16px;
            font-weight: 500;
            border-bottom: 1px solid #e5e6e7;
          }
          .content{
            padding: 15px 0;
            .comment{
              padding: 18px 0;
              float: left;
              width: 120px;
              .percent{
                color: #FE834D;
                text-align: center;
                font-size: 36px;
              }
              .text{
                text-align: center;
                color: #999;
              }
            }
            .rate-group{
              float: left;
              .rate-container{
                margin: 10px 0;
                .rate-value{
                  vertical-align: middle;
                  display: inline-block;
                  height: 24px;
                  width: 138px;
                  border: 1px solid #e5e6e7;
                  margin-right: 15px;
                  .rate-content1{
                    background-color: #43C97C;
                    height: 100%;
                  }
                  .rate-content2{
                    background-color: #41B7EF;
                    height: 100%;
                  }
                  .rate-content3{
                    background-color: #999;
                    height: 100%;
                  }
                }
              }
            }
            .btn-group{
              padding: 38px 0;
              float: right;
              .green-btn{
                width: 120px;
                height: 44px;
              }
            }
          }
        }
        .comment-box{
          padding: 20px 0;
          .comment-rate{
            margin-bottom: 10px;
          }
          .comment-input{

          }
          .comment-bottom{
            margin-top: 10px;
            .ion-image{
              float: left;
              background-color: #fff;
              font-size: 20px;
            }
            .img-container{
              float: left;
            }
            .comment-btn{
              float: right;
            }
          }
        }
        .comment-title{
          height: 44px;
          background-color: #f4f4f4;
          line-height: 44px;
          >ul{
            >li{
              float: left;
              margin: 0 20px;
            }
          }
        }
      }
      .right{
        float: left;
        width: 210px;
        .btn-group{
          text-align: center;
          margin-bottom: 10px;
          >button{
            font-size: 14px;
            line-height: 1.5;
            width: 100px;
            height: 30px;
          }
        }
        .xyd-container{
          .xyd-c-title{}
          .xyd-c-content{
            >ul{
              >li{
                &:last-child{
                  border-bottom: 0;
                }
                border-bottom: 1px solid #e5e6e7;
              }
            }
          }
        }
      }
    }
  }
</style>